package com.huika.renrench.control.main.epship.acty;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.huika.lib.utils.MoneyShowTool;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.login.activity.LoginActivity;
import com.huika.renrench.control.main.shoptf.gallery.ImageDetailAct;
import com.huika.renrench.control.main.shoptf.gallery.ProductImageArray;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.model.ProjectDetail;
import com.huika.renrench.support.bean.EnshipProject;
import com.huika.renrench.support.bean.LocationBean;
import com.huika.renrench.support.bean.LocationBean.MyLocationListener;
import com.huika.renrench.ui.GaodeMapRouteActivity;
import com.huika.renrench.utils.GaodeMapHelper;
import com.huika.renrench.utils.LoginUtils;
import com.huika.renrench.view.TitleBarHelper;

/**
 * @author chenyuan
 * @date：2015年6月2,下午2:15:30
 * @describe:创业项目详情activity
 */
public class EnProjectDetailActivity extends BaseAct implements
		Listener<RequestResult<ProjectDetail>>, MyLocationListener {
	public static final String PROJECT_TAG = "project";

	/** 图片 */
	private ImageView img_iv;
	/** 项目名称 */
	private TextView tv_name;
	/** 项目价格 */
	private TextView tv_price;
	/** 项目时长 */
	private TextView tv_time;
	/** 项目描述 */
	private TextView tv_desc;
	/** 商家名称 */
	private TextView tv_owner_name;
	/** 商家地址 */
	private TextView tv_owner_address;
	/** 点击查看相册 */
	private LinearLayout click_to_see_album;
	/** 距离 */
	private TextView tv_owner_distance;
	private EnshipProject project;
	private ProjectDetail projectDetail=new ProjectDetail();
	private TitleBarHelper titleBarHelper;

	private String projectId;
	private LocationBean locationBean;
	private GaodeMapHelper gaodeMapHelper;
	
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		super.initData();
		project = (EnshipProject) getIntent().getSerializableExtra(PROJECT_TAG);

		if (project == null) {
			Intent intent = getIntent();
			projectId = (String) intent.getExtras().get("projectId");
		} else {
//			projectId = project.projectId + "";
		}
		
		locationBean=GlobalApp.getInstance().locationBean;
		if (GlobalApp.getInstance().isLocated()) {
			getNetData();
		}else{
			startLocation();
		}
		
	}


	@Override
	public void setRootView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_project_detail);
	}

	@Override
	protected void initWidget() {
		// TODO Auto-generated method stub
		super.initWidget();
		

		titleBarHelper = new TitleBarHelper(this, -1, R.string.about);

		titleBarHelper.setLeftMsg("返回");
		titleBarHelper.setOnRightClickListener(this);

		initTopView();

		img_iv = (ImageView) findViewById(R.id.img_iv);
		tv_name = (TextView) findViewById(R.id.tv_name);

		tv_price = (TextView) findViewById(R.id.tv_price);

		tv_time = (TextView) findViewById(R.id.tv_time);
		tv_desc = (TextView) findViewById(R.id.tv_desc);
		tv_owner_name = (TextView) findViewById(R.id.tv_owner_name);
		tv_owner_address = (TextView) findViewById(R.id.tv_owner_address);
		click_to_see_album = (LinearLayout) findViewById(R.id.click_to_see_albumLoy);
		click_to_see_album.setOnClickListener(this);
		tv_owner_distance = (TextView) findViewById(R.id.tv_owner_distance);

		tv_owner_name.setOnClickListener(this);
		tv_owner_address.setOnClickListener(this);
		findViewById(R.id.icon_tell).setOnClickListener(this);

		/** 获取网络数据 **/
//		getNetData();

	}
	
	private void startLocation() {
		showLoadingDialog("定位中");
		gaodeMapHelper = new GaodeMapHelper(this);
		gaodeMapHelper.setmLocationListener(this);
		gaodeMapHelper.start();
	}

	@Override
	public void onStop() {
		super.onStop();
		if(gaodeMapHelper != null){
			gaodeMapHelper.stop();
		}
	}

	private void getUserId(JSONWrapAjaxParams ajaxParams) {
		String u_id = GlobalApp.getInstance().getUserId();
		if (!TextUtils.isEmpty(u_id)) {
			ajaxParams.putCommonTypeParam("userId", u_id);
		} else {
			ajaxParams.putCommonTypeParam("userId", "0");
		}
	}

	private void getNetData() {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("projectId", projectId);
		if (GlobalApp.getInstance().isLocated()) {
			ajaxParams.putCommonTypeParam("latitude", locationBean.latitude);
			 ajaxParams.putCommonTypeParam("longitude", locationBean.longtitude);
		}
		
		getUserId(ajaxParams);
		FormResultRequest<ProjectDetail> getResultRequest = new FormResultRequest<ProjectDetail>(
				UrlConstants.URL_PROJECT_DETAIL, this, this,
				new TypeToken<RequestResult<ProjectDetail>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		executeRequest(getResultRequest);

	}

	private void initTopView() {
		RelativeLayout rl_top_imgs = (RelativeLayout) findViewById(R.id.rl_top_imgs);
		LayoutParams layoutParams = (LayoutParams) rl_top_imgs
				.getLayoutParams();
		layoutParams.height = GlobalApp.getInstance().SCREEN_WIDTH * 390 / 640;
		rl_top_imgs.setLayoutParams(layoutParams);
	}

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		super.widgetClick(v);
		
		switch (v.getId()) {
		case R.id.icon_tell:// 拨号
			if (null != projectDetail) {
				if (!TextUtils.isEmpty(projectDetail.phone)) {
					Intent telIntent = new Intent(Intent.ACTION_DIAL);
					telIntent.setData(Uri.parse("tel:" + projectDetail.phone));
					startActivity(telIntent);
				}
//				String tell = TextUtils.isEmpty(projectDetail.phone) ? getString(R.string.about_tell)
//						: projectDetail.phone;
				
			}
			break;
		case R.id.click_to_see_albumLoy:// 相册
			showGallery();
			break;
		case R.id.tv_owner_name:// 地图路径
		case R.id.tv_owner_address:
			Intent goalIntent = new Intent(this, GaodeMapRouteActivity.class);
			goalIntent.putExtra("projectDetail", projectDetail);
			startActivity(goalIntent);
			break;
		case R.id.right:
			
			if (!LoginUtils.isLogin()) {
				showActivity(this, LoginActivity.class);
				return;
			}

			getAddCollect();
			break;
		}

	}

	private void getAddCollect() {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
//		ajaxParams.putCommonTypeParam("collectId", project.projectId);
		ajaxParams.putCommonTypeParam("type", "1");
		getUserId(ajaxParams);
		FormResultRequest<HashMap<String, String>> getResultRequest = new FormResultRequest<HashMap<String, String>>(
				UrlConstants.ADDCOLLECT, getAddCollectRsp, this,
				new TypeToken<RequestResult<HashMap<String, String>>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		executeRequest(getResultRequest);

	}

	private Listener<RequestResult<HashMap<String, String>>> getAddCollectRsp = new Listener<RequestResult<HashMap<String, String>>>() {

		@Override
		public void onResponse(RequestResult<HashMap<String, String>> result) {
			if (result != null && result.flag == 1) {
				// setAreaClassifyData(result.getRs());
				showToastMsg("关注成功！");
				titleBarHelper.setRightMsg("已关注");
				titleBarHelper.setRightMsgColor(getResources().getColor(
						R.color.color_969696));
				titleBarHelper.setOnRightClickListener(null);
			} else {
			}

			dismissLoadingDialog();
		}
	};

	protected List<ProductImageArray> imgUrls;
	private String[] imgs = {
			"http://img0.imgtn.bdimg.com/it/u=3766230679,95318279&fm=21&gp=0.jpg",
			"http://img1.imgtn.bdimg.com/it/u=2984036353,594873942&fm=21&gp=0.jpg",
			"http://img1.imgtn.bdimg.com/it/u=3594953304,3934544117&fm=21&gp=0.jpg" };

	private void showGallery() {
		imgUrls = new ArrayList<ProductImageArray>();
		/** 测试数据 */
		// for (int i = 0; i < imgs.length; i++) {
		// ProductImageArray bean = new ProductImageArray();
		// bean.setImageUrl(imgs[i]);
		// bean.setBigImageUrl(imgs[i]);
		// imgUrls.add(bean);
		// }
		/** 网络数据 */
		if (null!=projectDetail) {
			if (!projectDetail.imageArray.isEmpty()
					&& projectDetail.imageArray.size() > 0) {
				imgUrls.addAll(projectDetail.imageArray);

				Bundle bundle = new Bundle();
				bundle.putParcelableArrayList("imageListBean",
						(ArrayList<? extends Parcelable>) imgUrls);
				bundle.putString("imageDetailCheck", imgUrls.get(0)
						.getBigImageUrl());
				Intent intent = new Intent(this, ImageDetailAct.class);
				intent.putExtras(bundle);
				startActivity(intent);

			}
		}
		

	}

	@Override
	public void onResponse(RequestResult<ProjectDetail> result) {
		dismissLoadingDialog();
		if (result.flag == 1) {
			if (result.getRs() != null) {
				projectDetail = result.getRs();
				tv_owner_name.setText(projectDetail.shopName);
				tv_desc.setText(projectDetail.introduction);
				tv_time.setText(projectDetail.learningTime);
				tv_owner_distance.setText(projectDetail.getDistance());
				if (null!=projectDetail.imageArray&&projectDetail.imageArray.size()>0) {
					GlobalApp.loadImgLoader(img_iv, projectDetail.imageArray.get(0).getBigImageUrl());
				}

				titleBarHelper.setTitleMsg("项目详情");

//				if (projectDetail.projectName.length() > 10) {
//					titleBarHelper.setTitleMsg(projectDetail.projectName
//							.substring(0, 9) + "...");
//				} else {
//					titleBarHelper.setTitleMsg(projectDetail.projectName);
//				}

				tv_name.setText(projectDetail.projectName);
				if (projectDetail.tradePrice.equals("null")||projectDetail.tradePrice==null||projectDetail.tradePrice.equals("0")) {
					tv_price.setText("面议");
				}else{
					tv_price.setText("￥"
							+ MoneyShowTool.formatTwo(Double.valueOf(projectDetail.tradePrice)));
				}
				tv_owner_address.setText(projectDetail.address);

				if (projectDetail.isAttention) {
					titleBarHelper.setRightMsg("已关注");
					titleBarHelper.setOnRightClickListener(null);
					titleBarHelper.setRightMsgColor(getResources().getColor(
							R.color.color_969696));

				} else {
					titleBarHelper.setRightMsg("关注");
					titleBarHelper.setOnRightClickListener(this);
				}
			}

		}

	}

	@Override
	public void onErrorResponse(VolleyError error) {
		// TODO Auto-generated method stub
		super.onErrorResponse(error);
	}


	@Override
	public void onLocation(LocationBean locationBean) {
		// TODO Auto-generated method stub
		if(!TextUtils.isEmpty(locationBean.province)){
			GlobalApp.getInstance().setLocated(true);
//			initData();
		}else{//定位失败
			showToastMsg("定位失败");
			dismissLoadingDialog();
		}
		getNetData();
	}

}
